#!/bin/bash
# 遇到任何错误立即退出脚本
set -e

# --- 配置颜色变量 ---
# 使用 printf 来确保更好的兼容性
C_BLUE=$(printf '\033[34m')
C_GREEN=$(printf '\033[32m')
C_BOLD=$(printf '\033[1m')
C_RESET=$(printf '\033[0m')

# --- 脚本开始 ---
echo "${C_BLUE}====================================================${C_RESET}"
echo "${C_BLUE}🚀  Starting Build & Run Process for rCore Tutorial  🚀${C_RESET}"
echo "${C_BLUE}====================================================${C_RESET}"

# --- 阶段 1: 编译内核 ---
echo "\n${C_BOLD}[ 1/3 ] Compiling Kernel (release mode)...${C_RESET}"
cargo build --release
echo "${C_GREEN}✅ Build successful!${C_RESET}"

# --- 阶段 2: 转换文件格式 ---
echo "\n${C_BOLD}[ 2/3 ] Converting ELF to Binary format...${C_RESET}"
rust-objcopy --strip-all target/riscv64gc-unknown-none-elf/release/os -O binary target/riscv64gc-unknown-none-elf/release/os.bin
echo "${C_GREEN}✅ Stripped and converted to os.bin successfully!${C_RESET}"

# --- 阶段 3: 启动 QEMU ---
echo "\n${C_BOLD}[ 3/3 ] Starting QEMU Virtual Machine...${C_RESET}"
echo "${C_BLUE}----------------------------------------------------${C_RESET}"

qemu-system-riscv64 \
    -machine virt \
    -nographic \
    -bios ../bootloader/rustsbi-qemu.bin \
    -device loader,file=target/riscv64gc-unknown-none-elf/release/os.bin,addr=0x80200000
#    -s -S # 如果需要调试，请取消这一行的注释

# 脚本正常结束后打印成功信息
echo "${C_BLUE}----------------------------------------------------${C_RESET}"
echo "${C_GREEN}✅ QEMU has shut down. Process finished.${C_RESET}"